<?php

namespace App\Models;

use Dcat\Admin\Traits\HasDateTimeFormatter;

use Illuminate\Database\Eloquent\Model;
use Dcat\Admin\Traits\ModelTree;
class Config extends Model
{
    use HasDateTimeFormatter, ModelTree;    
    public $timestamps = false;


    // 父级ID字段名称，默认值为 parent_id
    protected $parentColumn = 'pid';

    // 排序字段名称，默认值为 order
    protected $orderColumn = 'listorder';

    // 标题字段名称，默认值为 title
    protected $titleColumn = 'name';


    public function buildSelectOptions(array $nodes = [], $parentId = 0, $prefix = '', $space = '&nbsp;')
    {
        $d = '├─';
        $prefix = $prefix ?: $d.$space;

        $options = [];

        if (empty($nodes)) {
            $nodes = $this->allNodes()->toArray();
        }

        foreach ($nodes as $index => $node) {
            if ($node[$this->getParentColumn()] == $parentId) {
                $currentPrefix = $this->hasNextSibling($nodes, $node[$this->getParentColumn()], $index) ? $prefix : str_replace($d, '└─', $prefix);

                $node[$this->getTitleColumn()] = $currentPrefix.$space.$node[$this->getTitleColumn()];

                $childrenPrefix = str_replace($d, str_repeat($space, 6), $prefix).$d.str_replace([$d, $space], '', $prefix);

                $children = $this->buildSelectOptions($nodes, $node[$this->getKeyName()], $childrenPrefix);

                $options[$node[$this->getKeyName()]] = $node[$this->getTitleColumn()];

                if ($children) {
                    $options += $children;
                }
            }
        }

        return $options;
    }
}
